﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MsgSender.models;
using log4net;

namespace MsgSender.buz
{
    public static class SendMsgBuz
    {
        private static ILog _log = LogManager.GetLogger(typeof(SendMsgBuz));
        /// <summary>
        /// 是否需要发送文字，需要发送的文字已经放入剪切板
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static bool SendMessage(CWindow.CWindow window)
        {
            bool fSend = true;
            try
            {
                UserModel user = new UserModel();
                user.Name = window.Caption;
                UserModel u = user.Get();
                //新的对话
                if (u == null)
                {
                    user.SendIndex = 0;
                    user.LastSendTime = DateTime.Now;
                    user.Add();
                }
                else//已经存在执行修改
                {
                    user = u;
                    //发送语句达到最大 并且 在周期内 直接退出无需发送
                    if (user.SendIndex+1 >= AppSetting.AppSettings.sendTextList.Count
                        && DateTime.Now < user.LastSendTime.AddHours(AppSetting.AppSettings.msgCycleTime))
                        return false;
                    user.SendIndex++;
                    user.LastSendTime = DateTime.Now;
                    user.Update();
                }

                //插入历史
                SendHistoryModel history = new SendHistoryModel();
                history.UserID = user.ID;
                history.SendTextIndex = user.SendIndex;
                history.SendText = AppSetting.AppSettings.sendTextList[history.SendTextIndex];
                history.SendDate = user.LastSendTime;
                history.Add();

                //把发送数据放入剪切板
                System.Windows.Forms.Clipboard.Clear();
                System.Windows.Forms.Clipboard.SetText(history.SendText);
            }
            catch(Exception e) {
                _log.Error(e);
            }

            return fSend;

        }
    }
}
